<?php
/**
 * Mobile's resolver
 */

namespace Hmw\Util;

class MobileLocale
{
    /**
     * @param $number
     * @return string|null|boolean
     * null:返回未知
     * false:文件各类操作失败
     */
    public static function query($number)
    {
        $src_path = dirname(__FILE__);
        $root = dirname($src_path);
        $config = require $src_path . '/config/config.php';
        $distinct = require $root . $config['mobile']['path'] . '/index.php';
        $suffix_list = $config['mobile']['suffix'];

        $suffix = substr($number, 0, 3);
        $area_field = intval(substr($number, 3, 4));

        $file = $root . $config['mobile']['path'] . '/data';
        $ret = array_search($suffix, $suffix_list);
        if ($ret === false) {
            return null;
        }
        $offset = ($ret * $config['mobile']['segment'] + $area_field) * $config['mobile']['bytes'];

        $fp = fopen($file ,'r');

        if (!$fp) {
            return null;
        }

        $ret = fseek($fp, $offset);

        if ($ret !== 0) {
            return false;
        }

        $target = fread($fp, $config['mobile']['bytes']);
        $target = unpack('S', $target)[1];
        $location = $distinct[$target];

        fclose($fp);

        if ($location === false) {
            return false;
        }

        $location = trim($location);
        return (!empty($location) && $location !== '未知') ? $location : null;
    }
}
